var tempFolder;

function CreatorPageBuilder () {
	PageBuilder.call(this);
}


CreatorPageBuilder.prototype = new PageBuilder();

CreatorPageBuilder.prototype.constructor = CreatorPageBuilder;


CreatorPageBuilder.prototype.build = function () {
	$("#creator_label").html(getDisplayString("creator_label_text"));
	$("#embed_tab").html(getDisplayString("embed_tab_caption"));
	$("#web_address_tab").html(getDisplayString("webaddress_tab_caption"));
	$("#imports_tab").html(getDisplayString("imports_tab_caption"));
	$("#web_folder_tab").html(getDisplayString("webfolder_tab_caption"));
	$("#widgets_tab").html(getDisplayString("widgets_tab_caption"));
	$("#embed_label").html(getDisplayString("embed_caption"));
	$("#embed_instruction").html(getDisplayString("embed_instruction_text"));
	$("label.widgetn	ame_label").html(getDisplayString("widgetname_caption"));
	$("label.iconchooser_label").html(getDisplayString("iconchooser_caption"));
	$("label.widgetdescription_label").html(getDisplayString("widgetdescription_caption"));
	$("label.widgetwidth_label").html(getDisplayString("widgetwidth_caption"));
	$("label.widgetheight_label").html(getDisplayString("widgetheight_caption"));
	$("span.submit_label").html(getDisplayString("submitbutton_caption"));
	$("#webaddress_instruction").html(getDisplayString("webaddress_instruction_text"));
	$("#webaddress_label").html(getDisplayString("webaddress_caption"));
	$("#import_instruction").html(getDisplayString("import_instruction_text"));
	$("label.choosefile_label").html(getDisplayString("choosefile_caption"));
	$("#webfolder_instruction").html(getDisplayString("webfolder_instruction_text"));
	$("div.loggedin_message").html(getDisplayString("not_signed_in"));
}





$(document).ready(function() {

	setLogin();
	buildPage ( new CreatorPageBuilder() );
	
	var u = getUser();

	$("#tabs").tabs();
	
	$("#fileupload").fileupload({
		dataType: 'text',
		url: store_rest_url+"/creator/widget",
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		formData: function (form){

			var u = getUser();
			var username = "hfiefsldkfjs"; // garbage to make it fail
			if ( u != null ) {
				username = u.username;
			}
			return [ {name: 'username', value: username }];
		},
		done: function (e, data){
			uploaded(data.result);
		},
		fail: widgetUploadFailed,
		progressall: function(e,data) {
			var progress = parseInt(data.loaded/data.total*100,10);
			$("#upload_percent").html(progress+"%");
		}
	});
	
	$("#mediafileupload").ajaxForm({
		dataType: "text",
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		error: mediaUploadFailed,
		success: saved
	});
	$("#embedform").ajaxForm({
		dataType: "text",
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		error: embedFailed,
		success: uploaded
	});
	$("#webaddressform").ajaxForm({
		dataType: "text",
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		error: webAddressFailed,
		success: uploaded
	});
	$("#sitefileupload").ajaxForm({
		dataType: "text",
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		error: sitefileUploadFailed,
		success: saved
	});
	var u = getUser();
	$("#hiddenusername").val(u.username);
	$("#embedformuser").val(u.username);
	
	$("#searchText").on('keydown', function(e) {
		if ( e.which == 13 ) {
			e.preventDefault();
			searchStore();
		}
	});
	
	$("#fileSelector").dialog({
		modal:true,
		autoOpen: false
	});
	
	buildIconChoosers();
	
});


function buildIconChoosers() {
	// get icon lists
	getIconList ( "flash", buildFlashIconChooser );
	getIconList ( "web", buildWebIconChooser );
	getIconList ( "url", buildWebAddressIconChooser );
	getIconList ( "general", buildGeneralIconChooser );
	
	
}


function buildFlashIconChooser ( iconList ) {
	buildIconChooser(iconList, "flash_icon_chooser");
}


function buildWebIconChooser ( iconList ) {
	buildIconChooser ( iconList, "web_icon_chooser");
}


function buildWebAddressIconChooser ( iconList ) {
	buildIconChooser ( iconList, "webaddress_icon_chooser" );
}


function buildGeneralIconChooser ( iconList ) {
	buildIconChooser ( iconList, "general_icon_chooser");
}

function widgetUploadFailed(e, data) {
	var status = data.jqXHR.status;
	if (status == 400 ) {
		alert ( "Upload Failed! The widget file was badly formatted.");
	}
	else { 
		alert ( "Upload Failed!  The server returned a status code of "+status );
	}
}

function embedFailed (jqXHR, textStatus, errorThrown ) {
	reportError ( jqXHR );
}

function webAddressFailed ( jqXHR, textStatus, errorThrown ) {
	reportError (jqXHR );
}

function reportError ( jqXHR ) {
	switch ( jqXHR.status ) {
		
		case 400:
			alert ("You must give your widget a name" );
			break;
		
		case 409:
			alert ("Sorry that widget name is already taken, please choose another" );
			break;
		
		case 415:
			alert ("Sorry, the only file type currently supported here is flash (.swf)");
			break;
			
		case 406:
			alert ("The web address you supplied is not valid.");
			break;
			
		default:
			alert ("The server returned an error: "+jqXHR.status );
	}
}

function mediaUploadFailed( jqXHR, textStatus, errorThrown ) {
	reportError ( jqXHR );
}


function sitefileUploadFailed ( jqXHR, textStatus, errorThrown ) {
	if ( jqXHR.status == 415 ) {
		alert ("Only standard zip files are supported for web folders");
	}
	else {
		reportError ( jqXHR );
	}
}


function checkWidgetName ( formName ) {
	var widgetName = $("#"+formName+" input[name='widgetname']").val();
	var restURL = store_rest_url+"/widgets/check/"+widgetName;
	$.ajax({
		url:restURL,
		type:"GET",
		dataType:"JSON",
		success: nameMessage,
		error: handleError,
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		}
	});
}


function handleError ( jqXHR, textStatus, errorThrown ) {
	reportError ( jqXHR );
}

function submitEmbed() {
	registerResponderForSignal ( "SubmitToCreator", sendEmbed );
	checkWidgetName("embedForm");
}


function submitMedia(){
	registerResponderForSignal("SubmitToCreator", sendMedia );
	checkWidgetName("mediaFileUpload");
}

function submitWebAddress () {
	registerResponderForSignal("SubmitToCreator", sendWebAddress );
	checkWidgetName("webaddressform");
}


function submitSite(){
	registerResponderForSignal("SubmitToCreator", sendSite );
	checkWidgetName("siteFileUpload");
}	

function nameMessage(msg) {
	if ( msg.message == "OK" ) {
		sendSignal("SubmitToCreator", null );
	}
	else if ( msg.message == "EXISTS" ) {
		if ( confirm(getDisplayString("widget_exists_overwrite"))) {
			sendSignal("SubmitToCreator", null );
		}
	}
	else if ( msg.message = "NOTALLOWED" ) {
		alert (getDisplayString("widget_name_taken"));
	}
}



function sendEmbed(){
	var u = getUser();
	var uri = store_rest_url+"/creator/embed";
	$("#embedform").attr('action', uri);
	$("embedformuser").val(u.username);
	$("#embedform").submit();
}


function sendMedia() {
	var u = getUser();
	var uri = store_rest_url+"/creator/file";
	$("#mediafileupload").attr('action', uri);
	$("#hiddenusername").val(u.username);
	$("#mediafileupload").submit();
}

function sendSite() {
	var u = getUser();
	var uri = store_rest_url +"/creator/file";
	$("#sitefileupload").attr('action', uri);
	$("#hiddenusername").val(u.username);
	$("#sitefileupload").submit();
}


function sendWebAddress() {
	var u = getUser();
	var uri = store_rest_url +"/creator/webaddress";
	$("#webaddressform").attr('action', uri );
	$("#webaddressform").submit();
}


function uploadGadget () {
	var user = getUser();
	if ( user == null ) {
		alert("Sorry you have been inactive too long, please log-in and try again");
	}
	// TODO some better format checking for the input fields
	var gadgetName = $("#gadgetName").val();
	var gadgetUrl = $("#uploadUrl").val();
	var gadgetData = {gadgetname: gadgetName, uploadrul: gadgetUrl, username: user.username};
	var uri = store_rest_url+"/creator/gadget";
	$.ajax({
		type: "POST",
		url: uri,
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		data: gadgetData,
		dataType: "text",
		success: saved
		
	});
}


function uploaded ( widgetJSON )
{
	var w = $.parseJSON(widgetJSON);
	if ( $.isArray(w) ) {
		w = w[0];
	}
	showWidgetView(w.id);
}




function saved(uploadResults) {
	var uploadResults = $.parseJSON(uploadResults);
	
	if ( uploadResults.uploadMessage == "OK" ) {
		var w = uploadResults.widgetProfile;
		showWidgetView(w.id);
		return;
	}
	else if ( uploadResults.uploadMessage == "NONE" ) {
		alert("No HTML files in archive");
		return;
	}
	else {
		// must be choose
		selectFileName ( uploadResults );
	}
	//if ( $.isArray(w) ) {
	//	w = w[0];
	//}
	//goToMyWidgets(w.id);
	//forwardToFunctionalities( w.id);
}


function selectFileName ( uploadResults ) {
	var fileList = uploadResults.htmlFileList;
	tempFolder = uploadResults.widgetFolderPath;
	$("#fileNameChooserMessage").html(getDisplayString("choose_html_file"));
	// add buttons
	$("#fileNameChooser").html();
	for(var i = 0; i<fileList.length; i++ ) {
		var fileName = fileList[i];
		var button = '<p><input type="radio" id="radio'+i+'" name="radio"  value="'+fileName+'"/><label for="radio'+i+'">'+fileName+'</label></p>';
		$("#fileNameChooser").append(button);
	}
	$("#fileNameChooser").buttonset();
	$("#fileSelector").dialog("open");
	
}

function cancelSelectFileName() {
	$("#fileSelector").dialog("close");
}
/*
("widgetname") String title,
			@FormParam("widgetdescription") String description,
			@FormParam("widgetwidth") String width,
			@FormParam("widgetheight") String height,
			@FormParam("icon") String icon,
			@FormParam("chosenfilename") String chosenIndexFile,
			@FormParam("tempfoldername")
*/

function selectAFileNameAndBuild() {
	// get selected filename
	var selectedFile = $("input[name='radio']:checked").val();
	if ( selectedFile == null ) {
		alert("Please select a file name");
		return;
	}
	
	// get all the data from the form again
	var title = $("#sitefileupload input[name='widgetname']").val();
	var chosenIcon = $("#sitefileupload input[name='icon']:checked").val();
	var description = $("#sitefileupload textarea[name='widgetdescription']").val();
	var height = $("#sitefileupload input[name='widgetheight']").val();
	var width = $("#sitefileupload input[name='widgetwidth']").val();
	
	var postData = { widgetname: title, widgetdescription: description, widgetwidth: width, widgetheight: height, icon: chosenIcon, chosenfilename: selectedFile, tempfoldername: tempFolder};
	
	var uri = store_rest_url+"/creator/build";
	$.ajax({
		type: "POST",
		url: uri,
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		data: postData,
		dataType: "text",
		success: widgetBuilt
		
	});
	
	$("#fileSelector").dialog("close");

}

function widgetBuilt ( widgetJSON ) {
	var w = $.parseJSON(widgetJSON);
	showWidgetView(w.id);
}

